package com.lipy.dubboconsumer.service;

import com.lipy.dubbocommon.entity.Staff;
import com.lipy.dubboconsumer.tool.TimeTools;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

@Component
public class CacheDemoService {

    @Cacheable(key = "#id",value = "staff",condition = "#id < 4")
    public Staff get(Integer id){
        TimeTools.sleep(50);
        Staff staff = new Staff();
        staff.setId(id);
        staff.setName("name"+id);
        System.out.println("CacheDemoService.get"+id);
        return staff;
    }

    /**
     * 缓存的是方法返回结果
     * @param staff
     * @return
     */
    @CachePut(value = "staff",key = "#staff.id")
    public Staff save(Staff staff){
        TimeTools.sleep(100);
        System.out.println("CacheDemoService.save staff"+ staff);
        return staff;
    }

    /**
     * beforeInvocation = true 执行实际方法前删除。默认是false
     * @param id
     * @return
     */
    @CacheEvict(value = "staff",key = "#id", beforeInvocation = true)
    public int delete(Integer id){
        System.out.println("CacheDemoService.delete id"+id);
        TimeTools.sleep(10);
        return Integer.valueOf(1).equals(id)?1:0;
    }
}
